var db = require('./noteDatabaseHandler')
var url = require('url');
var querystring = require('querystring');
var secure = require('./secure');

function add(req, res) {
	var user = secure.getAuthenticatedUser(req, res);
	if (user != null) {
		res.setHeader('Content-Type', 'text/plain');
		var params = querystring.parse(url.parse(req.url).query);
		if (params['text'] != null) {
			var today = '2013-08-03'; //new date();
			db.addNote(params['text'], today, user.id);
			res.end('Note added');
		} else {
			res.end('No note added');
		}
	}
}

function show(req, res) {
	var user = secure.getAuthenticatedUser(req, res);
	if (user != null) {
		res.setHeader('Content-Type', 'text/plain');
		res.end(JSON.stringify(db.getAllNotes(null,null,user.id)));
	}
}

function remove(req, res) {
	var user = secure.getAuthenticatedUser(req, res);
	if (user != null) {
		res.setHeader('Content-Type', 'text/plain');
		var params = querystring.parse(url.parse(req.url).query);
		if (params['noteId'] != null) {
			var note = db.getNoteById(params['noteId']);
			if (note != null && note.user_id == user.id) {
				db.deleteNode(params['noteId']);
			}
		} else {
			res.end("Note ID required");
		}
	}
}

exports.show = show;
exports.add = add;
exports.remove = remove;